
function Last(array) {
    return array[array.length - 1];
}

var downloading = false;
//var pending_downloads = [];
//var have_to_show = true;

function OnReceivedMessage(message, sender, sendResponse) {
    if (downloading) {
        alert("Still downloading");
        return;
    }
    var count = 0;
    var errors = [];
    var ids = [];
    downloading = true;

    for (var i = 0; i < message.length; i++) {
        try {
            var file = message[i];
            var f_name = "es_1\\" + file.FullName.replace(" ", "_") + "\\" + Last(file.Url.split("/"));
            //alert("starting " + f_name);
            chrome.downloads.download({ url: file.Url, filename: f_name },
                                                 function (id) {
                                                     ids.push(id);
                                                     // pending_downloads.push(id);
                                                 });
            count++;
        } catch (e) {
            alert(e);
            errors.push(message[i].FullName + " " + message[i].Url);
        }
    }
    // da sistemare con query
    //try {
    //    
    //} catch (e) {
    //    alert("error erasing");
    //}
    alert("Downloaded with " + (message.length - count).toString() + " errors");
    if (errors.length != 0)
        alert(errors);
    //chrome.downloads.show(ids[0]);
    downloading = false;

}

//function OnDownloadChanged(downloadDelta)
//{
//    if (downloadDelta.state != null && downloadDelta.state.current == "complete" && downloadDelta.state.previous == "in_progress")
//    {
//        alert("Downloaded " + JSON.stringify(downloadDelta) + JSON.stringify(pending_downloads));
//        if (pending_downloads.indexOf(downloadDelta.id) != -1)
//        {
//            //pending_downloads = pending_downloads.filter(function (el) { return el == downloadDelta.id; });
//            if (have_to_show)
//            {
//                //show
//                have_to_show = false;
//            }
//            alert("aoskasdas");

//            chrome.downloads.erase({ id: downloadDelta.id }, function (args) { return; });
//        }
//    }
//}

chrome.runtime.onMessage.addListener(OnReceivedMessage);
chrome.downloads.onChanged.addListener(OnDownloadChanged);
